var ctx=window.daijia.ctx;
var gsid=window.daijia.gsid;
var gasStationName=window.daijia.gasStationName;
var serviceNo=window.daijia.serviceNo;
var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数
var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载

$(document).ready(function(){
	initdata(true);
	window.setInterval(function(){
		initdata(false);
	},1000*60);
    //添加评价
	$(document).on("click",".addReview",function(){
		$('#dialog_review').modal();
		$("#submit_form")[0].reset();
    });
    $("#close_modal").click(function(){
		$('#dialog_review').modal("hide");
	});
    $("#content").keyup(function(){
  	  $("#putWords").html($(this).val().length);

    });
  
    rat('rateChose',1);
  
    $("#starLevel").val(5);
  
    $("#rateDiv").html("5星");
  
    function rat(star,m){
	  	star= '#' + star;
	  	$(star).raty({
	  		path: ctx+"/assets/css/images",
	  		starOff: 'star-off-big.png',
	  		starOn: 'star-on-big.png',
	  		starHalf: 'star-half-big.png',
	  		size: 24,
	  		start: 5,
	  		half:true,
	  		targetKeep : true,
	  		number:5,
	  		score:5,
	  		click: function (score, evt) {
	  			$("#starLevel").val(score*m);
	  			$("#rateDiv").html(score*m+"星");
	  		}
	  	});
  }
    var thisButton;
    function deleteReview() {
      $.post(ctx+'/gasstation/deleteReview/'+thisButton.attr("data-value"),function(data){
          if(data.success){
          	thisButton.parent().parent().remove();
              $.scojs_message('删除成功', $.scojs_message.TYPE_OK);
              setTimeout(function(){
             	  window.location.reload(true);
              }, 1000);
          }else{
              $.scojs_message('删除失败', $.scojs_message.TYPE_ERROR);
          }
      },'json');
    }

    //删除评价
    $(document).on("click",".deletethis",function(){
        thisButton = $(this);
        var confirm = $.scojs_confirm({
          content: "你真的要删除该评价吗？",
          action:deleteReview
        });
        confirm.show();
    });

    $(document).on("click","#save",function(){
    	
    	if($("#clientName").val()==""){
			$.scojs_message("请输入客户姓名", $.scojs_message.TYPE_ERROR);
			return false;
		}
    	if($("#clientPhone").val()==""){
    		$.scojs_message("请输入客户手机号", $.scojs_message.TYPE_ERROR);
    		return false;
    	}
    	var phone=/^[0-9]*$/;
		if(!phone.test($("#clientPhone").val())){
			$.scojs_message("请输入正确的手机号", $.scojs_message.TYPE_ERROR);
			return false;
		}
		if($("#content").val()==""){
			$.scojs_message("请输入评价内容", $.scojs_message.TYPE_ERROR);
			return false;
		}
    	
		$.ajax({
	           type: "POST",
	           async : false,
	           url: ctx+"/gasstation/review",
	           data: {gasStationId :gsid, gasStationName:gasStationName, serviceNo:serviceNo, clientName:$("#clientName").val(),
	           clientPhone:$("#clientPhone").val(), score:$("#starLevel").val(), content:$("#content").val()},
	           dataType: "json",
	           success: function(data){
	           	if (data.success) {
	           		$.scojs_message('添加成功', $.scojs_message.TYPE_OK);
		                setTimeout(function(){
		               	  window.location.reload(true);
		                }, 1000);
	           	} else {
	           		$.scojs_message(data.message, $.scojs_message.TYPE_OK);
	           	}
	           }
	       });
    });
});
	
	
  function initdata(isappend){
	$.ajax({
        url : ctx+'/gasstation/reviewData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"gsid":gsid,
        	"pager.offset":offset,
        	"limit":limit
        },
        success : function(result){
        	var newcontent = '';
        	var totalElements=result.totalElements;
        	$("#NoData").text("");
        	
        	if(totalElements>0){
        		$(result.content).each(function(index,data){
        			var deleteButton="<div class='btn-group'><a href='#' data-value='"+data.id+"' class='btn btn-primary btn-xs deletethis'>删除</a></div>";
            		
	    newcontent+="<tr class='grid-data tr-hui'  >"+
					    "<td>"+data.content+"</td>"+
					    "<td>"+data.score+"</td>"+
					    "<td>"+data.clientName+"</td>"+
					    "<td>"+data.orderNo+"</td>"+
					    "<td>"+data.created+"</td>"+
						"<td>"+deleteButton+"</td>"+
					"</tr>";
        		});
        	}else{
        		$("#NoData").text("当前页面暂无记录 ");
        	}
        	if(!isappend){
        		$("#review_tbody .grid-data").remove();
        	}
        	$("#review_tbody").append(newcontent);
        	$("#review_tbody .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.content.length;
            		pageLoading=true;
            	}else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.content.length;
            			pageLoading=true;
            		}else{
            			pageLoading=false;
            		}
            	}
        	}
        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        	}else{
            		pageLoading=false;
            		hasShowPages=true;
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
        	}
        }
	});
}
  

Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}
